<?php

class cAppFacebook extends caApp implements iApp
{
	public function __construct(dtoFacebookAuth $paramSessionDTO)
	{
		parent::__construct(__DIR__);
		$this->sessionDTO = $paramSessionDTO;
	}

	/**
	* Get the redirect url
	*
	* @return string
	*/
	public function getRedirectUrl()
	{
		$url = $this->cfg['url']['redirect'];

		$query = '?' .
			http_build_query(array(	'client_id'	=> $this->cfg['key']['consumer_key'],
						'redirect_uri'	=> $this->cfg['url']['main'],
						'scope'		=> $this->cfg['perm']['scope']));

		return ($url . $query);
	}

	/**
	* Request for access token
	*
	* @return array keys - oauth_token, oauth_token_secret (optional)
	*/
	public function requestAccessToken($get_token)
	{
		if ( ! isset($get_token)) return NULL;

		$url = $this->cfg['url']['access_token'];
		$query = '?' .
			http_build_query(array(	'client_id'	=> $this->cfg['key']['consumer_key'],
						'redirect_uri'	=> $this->cfg['url']['main'],
						'client_secret'	=> $this->cfg['key']['consumer_secret'],
						'code'		=> $get_token));
		
		$this->oauth = new OAuth(   $this->cfg['key']['consumer_key'],
                                            $this->cfg['key']['consumer_secret'],
                                            OAUTH_SIG_METHOD_HMACSHA1,
                                            OAUTH_AUTH_TYPE_URI);
		$access_token_info = $this->oauth->getAccessToken($url . $query);

		if (is_array($access_token_info)
                    &&
                    array_key_exists('access_token', $access_token_info))
		{
			// save extras
			$this->oauth->setToken(	$access_token_info['access_token'],
						$this->cfg['key']['consumer_secret']);
			$query = $this->cfg['fetch']['me'];
			$query .= '?' .
                                    http_build_query(array('access_token' =>
                                                                $access_token_info['access_token']));		
			$this->oauth->fetch($query);
			$extras = json_decode($this->oauth->getLastResponse());
			$this->sessionDTO->user_id	= $extras->id;
			$this->sessionDTO->username	= $extras->username;
			$this->sessionDTO->name		= $extras->name;
			$this->sessionDTO->timezone	= $extras->timezone;
			$this->sessionDTO->access_token	= TRUE;

			$this->sessionDTO->oauth_token	= $access_token_info['access_token'];
		}

		return $this->sessionDTO;
	}

	/**
	* Get the access token from the internal session or request it
	*
	* @return array keys - oauth_token, oauth_token_secret (optional)
	*/
	public function getAccessToken($get_token = NULL)
	{
		$access_token = NULL;

		if ($this->sessionDTO->access_token)
		{
			$access_token = $this->sessionDTO;
		}
		else
		{
			$access_token = $this->requestAccessToken($get_token);
		}
		
		return $access_token;
	}
}

# EOF
